package com.example.app.pages.main.home.accountList.viewModel

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.example.app.data.bean.routeAccount.AccountRecord
import com.example.app.util.CacheUtil
import com.example.app.util.dateStrToDateLong

class AccountListPagingSource(var accountListViewModel: AccountListViewModel) :
    PagingSource<Int, AccountRecord>() {
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, AccountRecord> {
        return try {
            val page = params.key ?: 1
            //下拉刷新动画 开始
            if (page === 1) {
                accountListViewModel.flowUpdate_refreshing(true)
            }
            val response = accountListViewModel.request_getAccountRecord(
                CreatorId = CacheUtil.getUserId(),
                pageNum = page,
                //每页显示20条数据
                pageSize = 20,
                //日期范围
                dateRange = listOf(
                    dateStrToDateLong("2022-10-03").toString(),
                    dateStrToDateLong("2024-10-03").toString()
                ),
                AccountRelationPeopleId = null,
            ).await()
            //下拉刷新动画 结束
            accountListViewModel.flowUpdate_refreshing(false)

            LoadResult.Page(
                data = response.data!!.rows,
                prevKey = if (page == 1) null else page - 1,
                nextKey = if (response.data!!.rows.isEmpty()) null else page + 1
            )
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }

    override fun getRefreshKey(state: PagingState<Int, AccountRecord>): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1)
                ?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1)
        }
    }
}
